﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using MovieRental.Entities;

namespace MovieRental.EfRepositoryLibrary.Mappers
{
    public class LoanCartMapper 
        : BaseMapper<LoanCartInfo, Guid, LoanCart, LoanCart, MovieRentalEntitiesContainer>
    {
        private LoanMapper _loanMapper = new LoanMapper();

        public override void Convert(LoanCartInfo entity, LoanCart model)
        {
            model.Id = entity.Id;
            model.CustomerId = (entity.CustomerId == Guid.Empty) ? null : new Nullable<Guid>(entity.CustomerId);
            model.CartDiscountValue = entity.CartDiscountValue;
            model.LoanDate = entity.LoanDate;
            foreach (var loan in entity.Loans)
            {
                var correspondingModel = model.Loans.SingleOrDefault(x => x.Id == loan.Id);
                if (correspondingModel == null)
                    model.Loans.Add(_loanMapper.Convert(loan));
                else
                    _loanMapper.Convert(loan, correspondingModel);
            }
            foreach (var modelLoan in model.Loans.Where(x => !entity.Loans.Any(y => y.Id == x.Id)))
                model.Loans.Remove(modelLoan);
        }

        public override void ConvertBack(LoanCart model, LoanCartInfo entity)
        {
            entity.Id = model.Id;
            entity.CustomerId = (model.CustomerId == null) ? Guid.Empty : model.CustomerId.Value;
            entity.CartDiscountValue = model.CartDiscountValue;
            entity.LoanDate = model.LoanDate;
            entity.Loans.Clear();
            foreach (var loan in model.Loans)
                entity.Loans.Add(_loanMapper.ConvertBack(loan));
        }

        public override Guid SelectKey(LoanCart model)
        {
            return model.Id;
        }

        public override Guid SelectKey(LoanCartInfo entity)
        {
            return entity.Id;
        }

        public override ObjectSet<LoanCart> SelectObjectSet(MovieRentalEntitiesContainer context)
        {
            return context.LoanCarts;
        }
    }
}
